package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ASUS
 * Date: 2025-03-01
 * Time: 18:11
 */
public class TcpEchoServer {
    private ServerSocket serverSocket = null;
    private ExecutorService service = Executors.newCachedThreadPool();

    // 这个操作就会绑定端口号
    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    // 启动服务器
    public void start() throws IOException {
        System.out.println("服务器启动!");
        while (true) {
            Socket clientSocket = serverSocket.accept();
//            Thread t = new Thread(() -> {
//                try {
//                    processConnection(clientSocket);
//                } catch (IOException e) {
//                    throw new RuntimeException(e);
//                }
//            });
//            t.start();
            service.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    }
    // 通过这个方法来处理一个连接的逻辑
    private void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s:%d] 客户端上线!\n", clientSocket.getInetAddress().toString(),
                clientSocket.getPort());
        // 接下来就可以读取请求, 根据请求计算响应,返回响应三步走了
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream =clientSocket.getOutputStream()) {
            while (true) {
                // 1. 读取请求并解析, 为了方便, 直接使用 Scanner
                Scanner scanner = new Scanner(inputStream);
                if (!scanner.hasNext()) {
                    // 读取完毕, 客户端下线
                    System.out.printf("[%s:%d] 客户端下线!\n", clientSocket.getInetAddress().toString(),
                            clientSocket.getPort());
                    break;
                }
                // 这个代码暗含一个约定, 客户端发过来的请求, 得是文本数据, 同时, 还得带有空白符作为分割 (比如换行这种)
                String request = scanner.next();
                // 2. 根据请求计算响应
                String response = process(request);
                // 3. 把响应写回个客户端
                PrintWriter writer = new PrintWriter(outputStream);
                //  使用 PrintWriter 的 println 方法, 把响应返回给客户端
                //  用 println, 而不用 print, 就是为了在结尾加一个 \n, 方便客户端读取响应, 使用 scanner.next 读取
                writer.println(response);
                //  这里还需要加入一个 "刷新缓冲区" 操作
                writer.flush();
                //  日志, 打印当前的请求详情
                System.out.printf("[%s:%d] req: %s, resp: %s\n ", clientSocket.getInetAddress().toString(),
                        clientSocket.getPort(),request,response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            clientSocket.close();
        }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }
}
